#!/usr/bin/python3
import os
from .Entity import Entity
from .Biz_Method import Biz_Method
from utils import My_Util2


class Service_Base_Broker(Biz_Method):
    """
    业务接口经纪人基类
    """

    def __init__(self, context, entity: Entity) -> None:
        self.context = context
        self.entity = entity
        self.my_util2 = My_Util2.My_Util(self.context)

    def code_includes(self):
        """
        包引入
        """
        package = self.entity.package
        prefix = self.entity.table_name.split("_")[0].lower()
        entity_name = self.entity.name
        includes = list()

        includes.append(
            f"""import com.baomidou.mybatisplus.extension.plugins.pagination.Page;"""
        )
        includes.append(f"""import {package}.internal.entity.{entity_name};""")
        includes.append(f"""import {package}.internal.transaction.BusinessException;""")
        if self.entity.has_sort():
            includes.append(f"""import {package}.internal.model.SwapBO;""")
        includes.append(
            f"""import {package}.{prefix}.query.exists.{entity_name}Exists;"""
        )
        includes.append(f"""import {package}.{prefix}.bo.{entity_name}BO;""")
        includes.append(f"""import {package}.{prefix}.bo.{entity_name}UpdateBO;""")
        includes.append(f"""import {package}.{prefix}.query.{entity_name}QueryInfo;""")
        includes.append(f"""import {package}.{prefix}.service.I{entity_name}Service;""")
        includes.append(f"""import {package}.{prefix}.vo.{entity_name}VO;""")
        includes.append(f"""import org.springframework.stereotype.Component;""")
        includes.append(f"""import java.util.List;""")
        includes = self.my_util2.sort_import_order(includes)
        return "\r".join(includes)

    def code_save(self) -> str:
        """
        新增
        """
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public boolean save({entity_name}BO {object_name}BO) throws BusinessException {"{"}
        return {object_name}Service.save({object_name}BO);
    {"}"}
"""

    def code_remove_list(self) -> str:
        """
        删除
        """
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public boolean remove{entity_name}ByIds(String ids) throws BusinessException {"{"}
        return {object_name}Service.remove{entity_name}ByIds(ids);
    {"}"}
"""

    def code_update(self) -> str:
        """
        修改
        """
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public boolean update{entity_name}ById({entity_name}UpdateBO {object_name}UpdateBO) throws BusinessException {"{"}
        return {object_name}Service.update{entity_name}ById({object_name}UpdateBO);
    {"}"}
"""

    def code_nullify_or_revert(self) -> str:
        """
        修改
        """
        if not self.entity.has_status():
            return None
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public boolean nullifyOrRevertByIds(String ids) throws BusinessException {"{"}
        return {object_name}Service.nullifyOrRevertByIds(ids);
    {"}"}
"""

    def code_swap(self) -> str:
        """
        交换
        """
        if not self.entity.has_sort():
            return None
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public boolean swap{entity_name}(SwapBO swapBO) throws BusinessException {"{"}
        return {object_name}Service.swap{entity_name}(swapBO);
    {"}"}
"""

    def code_get(self) -> str:
        """
        按ID获取
        """
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public {entity_name}VO getById(Long id) {"{"}
        return {object_name}Service.getById(id);
    {"}"}
"""

    def code_get_by_condition(self) -> str:
        """
        按条件获取
        """
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public {entity_name}VO getByCondition({entity_name}Exists {object_name}Exists) {"{"}
        return {object_name}Service.getByCondition({object_name}Exists);
    {"}"}
"""

    def code_page(self) -> str:
        """
        分页
        """
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public Page<{entity_name}VO> getPageByQueryInfo({entity_name}QueryInfo {object_name}QueryInfo, Page<{entity_name}> p) {"{"}
        return {object_name}Service.getPageByQueryInfo({object_name}QueryInfo, p);
    {"}"}
"""

    def code_list(self) -> str:
        """
        分页
        """
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public List<{entity_name}VO> list({entity_name}Exists {object_name}Exists) {"{"}
        return {object_name}Service.list({object_name}Exists);
    {"}"}
"""

    def code_next_sort(self) -> str:
        """
        获取下一个排序号
        """
        if not self.entity.has_sort():
            return None
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public Integer getNextSortNumber() {"{"}
        return {object_name}Service.getNextSortNumber();
    {"}"}
"""

    def code_exists(self) -> str:
        """
        存在性
        """
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        return f"""
    public boolean exists({entity_name}Exists {object_name}Exists) {"{"}
        return {object_name}Service.exists({object_name}Exists);
    {"}"}
"""

    def code(self):
        author = self.entity.author
        package = self.entity.package
        entity_name = self.entity.name
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment

        includes = self.code_includes()

        codes = list()
        save = self.code_save()
        codes.append(save)
        remove_list = self.code_remove_list()
        codes.append(remove_list)
        update = self.code_update()
        codes.append(update)
        nullify_or_revert = self.code_nullify_or_revert()
        if nullify_or_revert is not None:
            codes.append(nullify_or_revert)
        swap = self.code_swap()
        if swap is not None:
            codes.append(swap)
        get = self.code_get()
        codes.append(get)
        # get_by_condition = self.code_get_by_condition()
        # codes.append(get_by_condition)
        page = self.code_page()
        codes.append(page)
        code_list = self.code_list()
        codes.append(code_list)
        next_sort = self.code_next_sort()
        if next_sort is not None:
            codes.append(next_sort)
        exists = self.code_exists()
        codes.append(exists)
        codes = "\r".join(codes)

        return f"""package {package}.{self.context["code_storage"]["root"]}.broker;

{includes}

/**
 * <p>
 * {comment}业务接口经纪人基类
 * </p>
 *
 * @author {author}
 */
@Component
public class {entity_name}ServiceBaseBroker {'{'}

    private final I{entity_name}Service {object_name}Service;

    public {entity_name}ServiceBaseBroker(final I{entity_name}Service {object_name}Service) {"{"}
        this.{object_name}Service = {object_name}Service;
    {"}"}

    protected I{entity_name}Service getService() {"{"}
        return {object_name}Service;
    {"}"}
{codes}
{'}'}
"""

    def save_file(self, dir):
        _target_dir = os.path.join(dir, self.context["code_storage"]["root"], "broker")
        if not os.path.exists(_target_dir):
            os.makedirs(_target_dir)
        with open(
            os.path.join(
                _target_dir, "{}ServiceBaseBroker.java".format(self.entity.name)
            ),
            mode="w",
            encoding="utf-8",
        ) as f:
            f.write(self.code())
